import { Module } from 'vuex'
import { dynamicRoutes } from '@/router/dynamicRoutes'
import { generateMenusFromRoutes } from '@/router/dynamicRoutes'
import { getMenuList } from '@/api/menu'

interface PermissionState {
  routes: any[]
  menus: any[]
  addRoutes: any[]
}

const permissionModule: Module<PermissionState, any> = {
  namespaced: true,
  state: {
    routes: [],
    menus: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = routes
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    }
  },
  actions: {
    // 生成动态路由
    generateRoutes({ commit }, roleId) {
      return new Promise(async resolve => {
        try {
          // 1. 获取当前用户菜单权限（树形结构）
          const { data: menuTree } = await getMenuList();
          // 2. 过滤出有权限的路由（支持树形 menuCodes）
          const accessedRoutes = filterAsyncRoutes(dynamicRoutes, menuTree);
          console.log('accessedRoutes:', accessedRoutes);
          // 3. 生成菜单
          const menus = generateMenusFromRoutes(accessedRoutes);
          
          commit('SET_ROUTES', accessedRoutes);
          commit('SET_MENUS', menus);
          resolve(accessedRoutes);
        } catch (error) {
          console.error('生成路由失败:', error);
          resolve([]);
        }
      });
    }
  }
}

// 规范化路径比较
function normalizePath(path: string): string {
  if (!path) return '';
  // 转为小写，去除前后斜杠，统一格式
  return path.toLowerCase().replace(/^\/+|\/+$/g, '');
}

// 根据菜单树过滤路由
// function filterAsyncRoutes(routes: any[], menuTree: any[]): any[] {
//   return routes.filter(route => {
//     // 检查当前路由是否有权限
//     const hasPermission = checkPermissionInMenuTree(route, menuTree);
    
//     // 如果有子路由，递归过滤
//     if (route.children) {
//       route.children = filterAsyncRoutes(route.children, menuTree);
//       // 如果当前路由没有权限，但子路由有权限，则保留当前路由
//       return route.children.length > 0 || hasPermission;
//     }
    
//     return hasPermission;
//   });
// }
function filterAsyncRoutes(routes: any[], menuTree: any[]): any[] {
  return routes.filter(route => {
    // 检查当前路由是否有权限
    const hasPermission = checkPermissionInMenuTree(route, menuTree);
    
    // 如果有子路由，递归过滤
    if (route.children) {
      route.children = filterAsyncRoutes(route.children, menuTree);
      // 只有当自身有权限或子路由有权限时才保留
      return hasPermission || route.children.length > 0;
    }
    
    return hasPermission;
  }).map(route => {
    // 过滤后，确保只有有权限的路由被保留
    if (route.children) {
      // 如果自身没有权限，但子路由有权限，创建一个新的路由对象
      if (!checkPermissionInMenuTree(route, menuTree) && route.children.length > 0) {
        return {
          ...route,
          meta: {
            ...route.meta,
            hideInMenu: true // 在菜单中隐藏
          }
        };
      }
    }
    return route;
  });
}
// 检查路由是否在菜单树中有权限
function checkPermissionInMenuTree(route: any, menuTree: any[]): boolean {
  for (const menu of menuTree) {
    // 匹配规则：比较规范化后的路径
    const routePath = normalizePath(route.path);
    const menuPath = normalizePath(menu.url);
    
    // 如果路由有meta.menuCode，优先使用menuCode匹配
    if (route.meta?.menuCode && route.meta.menuCode === menu.menuCode) {
      return true;
    }
    
    // 其次使用路径匹配
    if (routePath && menuPath && routePath === menuPath) {
      return true;
    }
    
    // 递归检查子菜单
    if (menu.children?.length) {
      if (checkPermissionInMenuTree(route, menu.children)) {
        return true;
      }
    }
  }
  return false;
}

export default permissionModule;